package com.luck.easyfoodbatch.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.DiscountAdapter;
import com.luck.easyfoodbatch.adapter.GoodsImageHolderView;
import com.luck.easyfoodbatch.adapter.PeriodfoAdapter;
import com.luck.easyfoodbatch.custom.RoundedImageView;
import com.luck.easyfoodbatch.custom.SharePopupWindows;
import com.luck.easyfoodbatch.dialog.ShowProgressDialog;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.glide.GlideCircleTransform;
import com.luck.easyfoodbatch.mvp.home.GoodsInfoModel;
import com.luck.easyfoodbatch.mvp.home.GoodsInfoPresenter;
import com.luck.easyfoodbatch.mvp.home.GoodsInfoView;
import com.luck.easyfoodbatch.mvp.mine.CollectModel;
import com.luck.easyfoodbatch.mvp.mine.GetBatchesModel;
import com.luck.easyfoodbatch.mvp.mine.GetBatchesPresenter;
import com.luck.easyfoodbatch.mvp.mine.GetBatchesView;
import com.luck.easyfoodbatch.mvp.model.Batches;
import com.luck.easyfoodbatch.mvp.model.GoodModel;
import com.luck.easyfoodbatch.mvp.model.OrderJoin;
import com.luck.easyfoodbatch.mvp.model.PlaceOrderByM;
import com.luck.easyfoodbatch.mvp.order.OrderJoinCartModel;
import com.luck.easyfoodbatch.mvp.order.OrderJoinCartPresenter;
import com.luck.easyfoodbatch.mvp.order.OrderJoinCartView;
import com.luck.easyfoodbatch.mvp.order.PlaceOrderByModel;
import com.luck.easyfoodbatch.mvp.order.PlaceOrderByPresenter;
import com.luck.easyfoodbatch.mvp.order.PlaceOrderByView;
import com.luck.easyfoodbatch.ui.ConfirmOrderActivity;
import com.luck.easyfoodbatch.ui.ExchangeActivity;
import com.luck.easyfoodbatch.ui.LoginActivity;
import com.luck.easyfoodbatch.ui.ShopHomeActivity;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.SharedPreferencesUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.util.XLHRatingBar;
import com.luck.easyrecyclerview.decoration.DividerGridItemLineDecoration;
import com.luck.easyrecyclerview.swipe.MyLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author：luck
 * project：EasyFoodBatch
 * package：com.luck.easyfoodbatch.fragment
 * email：893855882@qq.com
 * data：16/9/30
 */
public class ShopDetailsFragment extends BaseFragment implements GoodsInfoView, OnItemClickListener, PlaceOrderByView, OrderJoinCartView, GetBatchesView {

    private View rootView;
    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.iv_icon)
    RoundedImageView ivIcon;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.rl_all_shop)
    RelativeLayout rl_all_shop;
    @BindView(R.id.rl_go_shop)
    RelativeLayout rl_go_shop;
    @BindView(R.id.rl_period)
    RelativeLayout rl_period;
    @BindView(R.id.tv_shop_title)
    TextView tv_shop_title;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_place)
    TextView tv_place;
    @BindView(R.id.tv_spec)
    TextView tv_spec;
    @BindView(R.id.tv_stock)
    TextView tv_stock;

    @BindView(R.id.tv_starting)
    TextView tv_starting;
    @BindView(R.id.iv_expiring)
    ImageView iv_expiring;
    @BindView(R.id.ratingBar3)
    XLHRatingBar ratingBar3;
    @BindView(R.id.ll_share)
    LinearLayout ll_share;
    @BindView(R.id.rl_shop)
    RelativeLayout rl_shop;
    @BindView(R.id.tv_single_money)
    TextView tv_single_money;
    @BindView(R.id.tv_single_price)
    TextView tv_single_price;
    @BindView(R.id.tv_single_spec)
    TextView tv_single_spec;
    @BindView(R.id.tv_is_ydx)
    TextView tv_is_ydx;
    @BindView(R.id.tv_is_by)
    TextView tv_is_by;
    @BindView(R.id.tv_is_coup)
    TextView tv_is_coup;
    private DiscountAdapter adapter;
    private List<GoodModel.DataBean.DiscountBean> list = new ArrayList<>();
    private List<GoodModel.DataBean.DiscountBean> copyList = new ArrayList<>();
    private List<List<Batches.DataBean>> infos = new ArrayList<>();
    private GoodsInfoModel infoModel;
    private String gid = "";
    private List<GoodModel.DataBean.ThumbsBean> thumbs = new ArrayList<>();
    private CollectModel collectModel;
    private GoodModel.DataBean data;
    private String shop_name = "", shop_avatar = "", shop_id = "", batch_id = "", batch_text = "";
    private int score = 0, isCollect = 0;
    private GetBatchesModel batchesModel;
    private OrderJoinCartModel joinCartModel;
    public String toChatUsername = "";
    private PlaceOrderByModel orderByModel;
    private String address_id = "";
    private String p_id = "3";
    private ShowProgressDialog dg;
    private int existVoucher = 0;
    private String vids = "";
    private String share_title = "易食批", share_url = "";
    public String share_text = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_shop_scrollview, container, false);
            ButterKnife.bind(this, rootView);
            initViews();
        }
        return rootView;
    }


    private void initViews() {
        ViewGroup.LayoutParams para = convenientBanner.getLayoutParams();//获取按钮的布局2、修改布局中的height，width属性
        para.width = App.screenWidth;//修改宽度
        para.height = App.screenWidth;//修改高度3、重新设置修改后的布局给控件
        convenientBanner.setLayoutParams(para);
        dg = new ShowProgressDialog(getActivity());
        gid = getActivity().getIntent().getStringExtra("gid");
        p_id = (String) SharedPreferencesUtil.getData(getActivity(), HttpUtil.P_ID, "3");
        share_url = "http://yishipi.com.cn/yspShare/goodsShare.html?gid=" + gid + "&sid=" + p_id;
        // 获取批次信息
        batchesModel = new GetBatchesPresenter(this, mContext);
        infoModel = new GoodsInfoPresenter(this, mContext);
        dg.setContent(getString(R.string.app_loading));
        dg.show();
        infoModel.goodsInfo(gid, p_id, 0);
        MyLayoutManager mLayoutManager = new MyLayoutManager(getActivity());
        mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(mLayoutManager);
        adapter = new DiscountAdapter(getActivity());
        adapter.setDiscounts(list);
        recyclerView.setAdapter(adapter);
    }

    @OnClick({R.id.rl_go_shop, R.id.rl_all_shop, R.id.tv_is_coup, R.id.rl_period, R.id.ll_share, R.id.rl_shop})
    public void onClick(View view) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.rl_go_shop:
                bundle.putString("shop_id", shop_id);
                bundle.putString("toChatUsername", toChatUsername);
                startAct(ShopHomeActivity.class, bundle);
                break;
            case R.id.rl_all_shop:
                bundle.putInt("type", 1);
                bundle.putString("shop_id", shop_id);
                bundle.putString("toChatUsername", toChatUsername);
                startAct(ShopHomeActivity.class, bundle);
                break;
            case R.id.rl_shop:
                bundle.putString("shop_id", shop_id);
                bundle.putString("toChatUsername", toChatUsername);
                startAct(ShopHomeActivity.class, bundle);
                break;
            case R.id.rl_period:
                showProgressDialog(getString(R.string.app_loading));
                batchesModel.getBatches(gid, p_id, 1);
                new PopupWindows(mContext, view, 0, 0);
                break;
            case R.id.ll_share:
                if (!isCheckedLogin()) {
                    startAct(LoginActivity.class);
                } else {
                    new SharePopupWindows(getActivity(), share_title, share_text, share_url, getView());
                }
                break;
            case R.id.tv_is_coup:
                bundle.putString("vids", vids);
                intent.setClass(mContext, ExchangeActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, 200);
                break;
        }
    }

    @Override
    public void onItemClick(int position) {

    }

    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
        if (convenientBanner != null) {
            convenientBanner.startTurning(2000);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (convenientBanner != null) {
            convenientBanner.stopTurning();
        }
    }


    /**
     * 选择保质期
     */
    private String thumb = "";
    private String price_range = "";
    private String single_price_range = "";
    private String packageX = "";
    private String total_stock = "";
    private String price = "";
    private String specifications = "";
    private String sold_least_num = "0";// 起批量
    private TextView tv_singe_price, tv_singe_money;

    public class PopupWindows extends PopupWindow {

        public PopupWindows(final Context mContext, View parent, int type, int flag) {
            super(mContext);
            View view = View.inflate(mContext, R.layout.pop_period, null);
            final LinearLayout ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
            RelativeLayout rl_root = (RelativeLayout) view.findViewById(R.id.rl_root);
            final RelativeLayout rl_title = (RelativeLayout) view.findViewById(R.id.rl_title);
            ImageView iv_close = (ImageView) view.findViewById(R.id.iv_close);
            ImageButton left_back = (ImageButton) view.findViewById(R.id.left_back);
            Button btn_addShopping = (Button) view.findViewById(R.id.btn_addShopping);
            Button btn_recharge = (Button) view.findViewById(R.id.btn_recharge);
            LinearLayout ll_sub = (LinearLayout) view.findViewById(R.id.ll_sub);
            LinearLayout ll_add = (LinearLayout) view.findViewById(R.id.ll_add);
            final EditText et_number = (EditText) view.findViewById(R.id.et_number);
            tv_singe_money = (TextView) view.findViewById(R.id.tv_money);// 箱价
            TextView tv_stock = (TextView) view.findViewById(R.id.tv_stock);
            TextView tv_starting = (TextView) view.findViewById(R.id.tv_starting);
            ImageView iv_banner = (ImageView) view.findViewById(R.id.iv_banner);
            tv_singe_price = (TextView) view.findViewById(R.id.tv_singe_money);// 单价
            joinCartModel = new OrderJoinCartPresenter(ShopDetailsFragment.this, getActivity());
            if (data != null) {
                thumb = data.getThumb();

                price_range = data.getPrice_range();
                single_price_range = data.getSingle_price_range();
                packageX = data.getPackageX();
                total_stock = data.getTotal_stock();
                price = data.getMarket_price();
                specifications = data.getSpecifications();
                sold_least_num = data.getSold_least_num();
                if (!Tools.isNull(thumb)) {
                    String path = "";
                    if (thumb.startsWith("http")) {
                        path = thumb;
                    } else {
                        path = HttpUtil.IMG_THUMB_BASE_URL + thumb;
                    }
                    Glide.with(mContext)
                            .load(path)
                            .centerCrop()
                            .placeholder(R.mipmap.loading_4b3)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(iv_banner);
                } else {
                    iv_banner.setImageResource(R.mipmap.loading_4b3);
                }
//                String single = tempMoney(data.getSingle_price());
//                if (!Tools.isNull(single)) {
//                    tv_singe_money.setText("单价：" + single);
//                } else {
//                    tv_singe_money.setText("单价：￥0.00");
//                }
//
//                String price = tempMoney(data.getPrice());
//                if (!Tools.isNull(price)) {
//                    tv_singe_price.setText("箱价：" + price + "/" + packageX);
//                } else {
//                    tv_singe_price.setText("箱价：￥0.00/件");
//                }
                if (!Tools.isNull(total_stock)) {
                    tv_stock.setText("总库存：" + total_stock);
                } else {
                    tv_stock.setText("总库存：0件");
                }

                tv_starting.setText("起批量：≥" + sold_least_num);
                et_number.setText(sold_least_num + "");
            }

            switch (type) {
                case 0:
                    // 保质期点击进来的
                    btn_addShopping.setVisibility(View.VISIBLE);
                    btn_recharge.setVisibility(View.VISIBLE);

                    btn_recharge.setText("立即购买");
                    btn_recharge.setTag(0);
                    break;
                case 1:
                    // 加入购物车或立即购买点击进来的
                    btn_addShopping.setVisibility(View.GONE);
                    btn_recharge.setVisibility(View.VISIBLE);
                    btn_recharge.setTag(1);
                    btn_recharge.setText("确定");
                    btn_recharge.setBackgroundResource(R.drawable.btn_anniu_bg);
                    break;
            }

            if (!Tools.isNull(total_stock)) {
                sumSize = Integer.parseInt(total_stock);
            }

            String rechargeText = btn_recharge.getText().toString().trim();
            if (rechargeText.equals("立即购买")) {
                flag = 1;
            }
            btn_addShopping.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int sold = 0;
                    if (!Tools.isNull(et_number)) {
                        sold = Integer.parseInt(et_number.getText().toString().trim());
                    }
                    if (sumSize < sold) {
                        T.showToast(mContext, "sorry，该商品库存不足，请联系卖家~");
                        return;
                    }
                    String text = ((Button) view).getText().toString().trim();
                    if (!Tools.isNull(text) && text.equals("加入购物车")) {
                        showProgressDialog(getString(R.string.app_loading));
                        joinCartModel.orderJoinCart(gid, batch_id, et_number.getText().toString().trim(), p_id);
                        dismiss();
                    }
                }
            });

            final int finalFlag = flag;
            btn_recharge.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!isCheckedLogin()) {
                        startAct(LoginActivity.class);
                        return;
                    }
                    int sold = 0;
                    if (!Tools.isNull(et_number)) {
                        sold = Integer.parseInt(et_number.getText().toString().trim());
                    }
                    if (sumSize < sold) {
                        T.showToast(mContext, "sorry，该商品库存不足，请联系卖家~");
                        return;
                    }
                    // 确定
                    if (finalFlag == 1) {
                        // 立刻购买 不加入购物车
                        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
                        if (user != null) {
                            User.DefaultAddressBean item = user.getDefault_address();
                            if (item != null) {
                                if (p_id.equals(item.getAddress_id())) {
                                    address_id = item.getAddress_id();
                                }
                            }
                        }
                        orderByModel = new PlaceOrderByPresenter(ShopDetailsFragment.this, mContext);
                        showProgressDialog("正在下单，请稍候……");
                        orderByModel.requestPlaceOrderBy(gid, batch_id, et_number.getText().toString().trim(), address_id, "");
                    } else {
                        showProgressDialog(getString(R.string.app_loading));
                        joinCartModel.orderJoinCart(gid, batch_id, et_number.getText().toString().trim(), p_id);
                    }
                    dismiss();
                }
            });

            ll_add.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String number = et_number.getText().toString().trim();
                    int num = Integer.parseInt(number);
                    num++;
                    et_number.setText(num + "");
                }
            });

            ll_sub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String number = et_number.getText().toString().trim();
                    int num = Integer.parseInt(number);
                    if (num > 1) {
                        num--;
                    }
                    et_number.setText(num + "");
                }
            });

            RecyclerView recycler = (RecyclerView) view.findViewById(R.id.periodRecycler);
            GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
            recycler.setItemAnimator(new DefaultItemAnimator());
            recycler.addItemDecoration(new DividerGridItemLineDecoration(App.getInstance().getContext().getResources().getColor(R.color.white)));
            recycler.setLayoutManager(manager);
            pAdapter = new PeriodfoAdapter(mContext);
            recycler.setAdapter(pAdapter);
            pAdapter.setOnItemClickListener(new PeriodfoAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position, View v) {
                    for (int i = 0; i < infos.size(); i++) {
                        List<Batches.DataBean> dataBeen = infos.get(i);
                        dataBeen.get(0).setChecked(false);
                    }
                    Batches.DataBean dataBean = infos.get(position).get(0);
                    if (dataBean.isChecked()) {
                        dataBean.setChecked(false);
                    } else {
                        dataBean.setChecked(true);
                        batch_id = dataBean.getBatch_id() + "";
                        batch_text = dataBean.getDue_date() + "";
                    }
                    String single_price = dataBean.getSingle_price();
                    single_price = tempMoney(single_price);
                    if (!Tools.isNull(single_price)) {
                        tv_singe_price.setText("单价：" + single_price);
                    } else {
                        tv_singe_price.setText("单价：￥0.00");
                    }
                    String price = dataBean.getPrice();
                    price = tempMoney(price);
                    if (!Tools.isNull(price)) {
                        tv_singe_money.setText("箱价：" + price);
                    } else {
                        tv_singe_money.setText("箱价：￥0.00");
                    }
                    pAdapter.notifyDataSetChanged();
                }
            });

            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss() {
                    setPhoneStatus();
                }
            });
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();
            final PopupWindow popupWindow = this;
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.popshow_anim));
            rl_root.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    hidePopupWindows(ll_popup, popupWindow);
                }
            });
            iv_close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    hidePopupWindows(ll_popup, popupWindow);
                }
            });
            left_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    getActivity().finish();
                }
            });

            setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss() {
                    if (convenientBanner != null) {
                        convenientBanner.startTurning(3500);
                    }
                }
            });
            //ToolbarUtil.setColorNoTranslucent(getActivity(), getResources().getColor(R.color.white));
        }
    }

    /**
     * 关闭 PopupWindows
     *
     * @param view
     * @param popupWindow
     */
    private void hidePopupWindows(View view, final PopupWindow popupWindow) {
        Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.pophidden_anim);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                popupWindow.dismiss();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(animation);
    }

    /**
     * 底部按钮点击事件回调
     *
     * @param type
     */
    private PeriodfoAdapter pAdapter;
    private int sumSize = 0;

    public void onActivityClick(int type) {
        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        if (user != null) {
            String shop_id = data.getShop_id();
            String uid = user.getUid() + "";
            if (shop_id.equals(uid)) {
                T.showAnimToast(mContext, "抱歉，您不能购买自己的商品~");
                return;
            }
        }
        batchesModel.getBatches(gid, p_id, 1);
        if (convenientBanner != null) {
            convenientBanner.stopTurning();
        }
        if (!Tools.isNull(total_stock)) {
            sumSize = Integer.parseInt(total_stock);
            if (sumSize <= 0) {
                T.showToast(mContext, "sorry，该商品库存不足，请联系卖家~");
                return;
            }
        }
        switch (type) {
            case 1:
                // 加入购物车
                new PopupWindows(mContext, rl_all_shop, 1, 0);
                break;
            case 2:
                //立即购买
                new PopupWindows(mContext, rl_go_shop, 1, 1);
                break;
        }
    }

    private int use_ydx = 0;

    @Override
    public void getGoodInfoSuccess(GoodModel model) {
        dg.dismiss();
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                data = model.getData();
                GoodModel.DataBean.VoucherInfo voucher_info = data.getVoucher_info();
                if (voucher_info != null) {
                    existVoucher = voucher_info.getExist_voucher();// 0无可用优惠券 1有可用
                    vids = voucher_info.getVids();
                    if (existVoucher == 1) {
                        tv_is_coup.setVisibility(View.VISIBLE);
                    } else {
                        tv_is_coup.setVisibility(View.GONE);
                    }
                }
                total_stock = data.getTotal_stock();
                thumbs = data.getThumbs();
                convenientBanner.setPages(
                        new CBViewHolderCreator<GoodsImageHolderView>() {
                            @Override
                            public GoodsImageHolderView createHolder() {
                                return new GoodsImageHolderView();
                            }
                        }, thumbs)
                        //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                        .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                        //设置指示器的方向
                        .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                        //.setPageTransformer(new DefaultTransformer())
                        //.setOnPageChangeListener(this)//监听翻页事件
                        .setOnItemClickListener(ShopDetailsFragment.this);
                String goods_name = data.getGoods_name();
                String marketPrice = data.getMarket_price();
                String specifications = data.getSpecifications();
                String packageX = data.getPackageX();
                String country_name = data.getCountry_name();
                String market_price = data.getMarket_price();
                int num = 0;
                if (!Tools.isNull(data.getNum())) {
                    num = Integer.parseInt(data.getNum());
                } else {
                    num = 0;
                }
                sold_least_num = data.getSold_least_num();
                String price_range = data.getPrice_range();
                single_price_range = data.getSingle_price_range();
                String single_price = data.getSingle_price();
                String single_specifications = data.getSingle_specifications();
                if (!Tools.isNull(market_price)) {
                    tv_single_price.setText("单品零售价：￥" + market_price);
                } else {
                    tv_single_price.setText("单品零售价：￥0");
                }


                if (!Tools.isNull(data.getUse_ydx())) {
                    use_ydx = Integer.parseInt(data.getUse_ydx());
                } else {
                    use_ydx = 1;
                }
                String free_post_num = data.getFree_post_num();
                String packageX1 = data.getPackageX();
                int is_free_post = 0;
                String free_post = data.getIs_free_post();
                if (!Tools.isNull(free_post)) {
                    is_free_post = Integer.parseInt(free_post);
                }

                switch (use_ydx) {
                    case 1:
                        tv_is_ydx.setText("不使用运东西物流");
                        tv_is_by.setText("");
                        break;
                    case 2:
                        tv_is_ydx.setText("");
                        switch (is_free_post) {
                            case 0:
                            case 1:

                                break;
                            case 2:
                                tv_is_by.setText("满" + free_post_num + packageX1 + "包邮");
                                break;
                        }
                        break;
                }


                String single_num = data.getSingle_num();
                String unit = "";
                if (!Tools.isNull(single_specifications)) {
                    unit = single_specifications;
                } else {
                    unit = "";
                }
                if (!Tools.isNull(single_specifications)) {
                    tv_single_spec.setText("单品规格：" + single_num + unit);
                } else {
                    tv_single_spec.setText("");
                }

                if (!Tools.isNull(goods_name)) {
                    tv_shop_title.setText(goods_name);
                    share_text = goods_name;
                    callBackValue.SendMessageValue(goods_name);
                } else {
                    tv_shop_title.setText("");
                }
                int is_collect = 0;
                if (!Tools.isNull(data.getIs_collect())) {
                    is_collect = Integer.parseInt(data.getIs_collect());
                } else {
                    is_collect = 0;
                }
                mCollectBackValue.SendMessageIsCollect(is_collect);
                single_price_range = tempMoney(single_price_range);
                if (!Tools.isNull(single_price_range)) {

                    tv_single_money.setText("单价：" + single_price_range);
                } else {
                    tv_single_money.setText("单价：￥0.00");
                }

                price_range = tempMoney(price_range);
                if (!Tools.isNull(price_range)) {
                    tv_money.setText("箱价：" + price_range + "/" + packageX);
                } else {
                    tv_money.setText("箱价：￥0.00/件");
                }

                if (!Tools.isNull(country_name)) {
                    tv_place.setText("产地：" + country_name);
                } else {
                    tv_place.setText("产地：");
                }

                if (!Tools.isNull(total_stock)) {
                    tv_stock.setText("库存：" + total_stock);
                } else {
                    tv_stock.setText("库存：0件");
                }
                if (!Tools.isNull(num)) {
                    tv_spec.setText("箱规：" + num + specifications + "/" + packageX);
                } else {
                    tv_spec.setText("箱规：");
                }
//                tv_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
//                if (!Tools.isNull(market_price)) {
//                    tv_price.setText("￥" + market_price + "/" + packageX);
//                } else {
//                    tv_price.setText("￥0件");
//                }

                tv_starting.setText("起批量：≥" + sold_least_num);
                int isExpiring = 0;
                if (!Tools.isNull(data.getIs_expiring())) {
                    isExpiring = Integer.parseInt(data.getIs_expiring());
                } else {
                    isExpiring = 2;
                }
                switch (isExpiring) {
                    case 1:
                        iv_expiring.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        iv_expiring.setVisibility(View.INVISIBLE);
                        break;
                }

                copyList = data.getDiscount();
                if (copyList == null) {
                    copyList = new ArrayList<>();
                }
                // 判断一下 折扣是否有不完整的 过滤掉
                list.clear();
                for (GoodModel.DataBean.DiscountBean dis : copyList) {
                    String count = dis.getCount();
                    String discount = dis.getDiscount();
                    if (!Tools.isNull(count) && !Tools.isNull(discount)) {
                        list.add(dis);
                    }
                }
                adapter.setSpec(specifications);
                adapter.setDiscounts(list);
                adapter.notifyDataSetChanged();
                GoodModel.DataBean.ShopBean shop = data.getShop();
                if (shop != null) {
                    shop_id = shop.getUid() + "";
                    shop_name = shop.getShop_name();
                    toChatUsername = shop.getShop_hx();
                    shop_avatar = shop.getShop_avatar();
                    if (!Tools.isNull(shop_name)) {
                        tvShopName.setText(this.shop_name);
                    } else {
                        tvShopName.setText(shop.getPhone());
                    }

                    if (!Tools.isNull(shop_avatar)) {
                        String path = "";
                        if (shop_avatar.startsWith("http")) {
                            path = shop_avatar;
                        } else {
                            path = HttpUtil.IMG_BASE_URL + shop_avatar;
                        }
                        Glide.with(App.getInstance().getContext())
                                .load(path)
                                .placeholder(R.mipmap.loading_4b3)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .transform(new GlideCircleTransform(getActivity()))
                                .into(ivIcon);
                    } else {
                        ivIcon.setImageResource(R.mipmap.loading_4b3);
                    }
                    if (!Tools.isNull(shop.getScore())) {
                        score = Integer.parseInt(shop.getScore());
                    } else {
                        score = 0;
                    }
                    ratingBar3.setCountSelected(score);
                }

            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }


    CallBackValue callBackValue;
    CollectBackValue mCollectBackValue;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        callBackValue = (CallBackValue) getActivity();
        mCollectBackValue= (CollectBackValue) getActivity();
    }

    //定义一个回调接口
    public interface CallBackValue {
        void SendMessageValue(String strValue);

    }

    public interface CollectBackValue {
        void SendMessageIsCollect(int isCollect);
    }

    public String getToChatUserName() {
        return toChatUsername;
    }

    public String getNickName() {
        return shop_name;
    }

//    @Override
//    public void collectSuccess(Collect model) {
//        if (model != null) {
//            if (model.getStatus() == HttpUtil.RESULT_OK) {
//                String msg = model.getMsg();
//                if (!Tools.isNull(msg) && msg.equals("收藏成功")) {
//                    iv_collection.setImageResource(R.mipmap.guanzhu02_sel_1x);
//                    tv_collection.setText("已收藏");
//                    if (data != null) {
//                        data.setIs_collect("1");
//                    }
//                } else if (!Tools.isNull(msg) && msg.equals("取消成功")) {
//                    iv_collection.setImageResource(R.mipmap.guanzhu02_def_1x);
//                    tv_collection.setText("收藏");
//                    if (data != null) {
//                        data.setIs_collect("0");
//                    }
//                }
//                T.showToast(mContext, msg);
//            } else {
//                T.showToast(mContext, model.getMsg());
//            }
//        }
//    }

    @Override
    public void orderJoinCartSuccess(OrderJoin model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                // 加入购物车 发送广播刷新购物车
                Intent intent = new Intent();
                intent.setAction("action.app.cart.refresh");
                getActivity().sendBroadcast(intent);

                T.showToast(mContext, model.getMsg());
            } else {
                String info = model.getMsg();
                if ("缺少参数:batch_id".equals(info)) {
                    T.showToast(mContext, "抱歉，该商品暂无批次信息无法购买，请联系卖家添加批次");
                } else {
                    T.showToast(mContext, model.getMsg());
                }
            }
        }
    }

    @Override
    public void batchesSuccess(Batches model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                infos = model.getData();
                if (pAdapter != null && infos != null && infos.size() > 0) {
                    infos.get(0).get(0).setChecked(true);
                    batch_id = infos.get(0).get(0).getBatch_id() + "";
                    batch_text = infos.get(0).get(0).getDue_date() + "";
                    String single_price = infos.get(0).get(0).getSingle_price();// 单价
                    String price = infos.get(0).get(0).getPrice();//箱价
                    single_price = tempMoney(single_price);
                    if (!Tools.isNull(single_price)) {
                        tv_singe_price.setText("单价：" + single_price);
                    } else {
                        tv_singe_price.setText("单价：￥0.00");
                    }
                    price = tempMoney(price);
                    if (!Tools.isNull(price)) {
                        tv_singe_money.setText("箱价：" + price);
                    } else {
                        tv_singe_money.setText("箱价：￥0.00");
                    }

                    pAdapter.setList(infos);
                    pAdapter.notifyDataSetChanged();
                }
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }


    @Override
    public void placeOrderBySuccess(PlaceOrderByM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                Bundle bundle = new Bundle();
                PlaceOrderByM.DataBean data = model.getData();
                bundle.putString("gid", gid);
                bundle.putSerializable("shop", data);
                bundle.putInt("use_ydx", use_ydx);// 是否使用运东西物流
                startAct(ConfirmOrderActivity.class, bundle);
            } else {
                String info = model.getMsg();
                if ("缺少参数:batch_id".equals(info)) {
                    T.showToast(mContext, "抱歉，该商品暂无批次信息无法购买，请联系卖家添加批次");
                } else {
                    T.showToast(mContext, model.getMsg());
                }
            }
        }
    }


    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }


    /**
     * 处理价格区间一样的问题
     *
     * @param str
     * @return
     */
    public static String tempMoney(String str) {
        if (!Tools.isNull(str)) {
            String[] split = str.split("~");
            if (split.length == 2) {
                String[] data = new String[split.length];
                for (int i = 0; i < split.length; i++) {
                    data[i] = split[i];
                }
                if (data[0].equals(data[1])) {
                    return data[0];
                } else {
                    return str;
                }
            } else {
                return str;
            }
        }
        return "";
    }

}
